package org.dromara.system.cloud;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.system.domain.SysTenant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.Duration;

import static org.dromara.system.cloud.CloudConsts.*;

@Component
@Slf4j
public class MiniCloudApi {


    @Value("${cloud.env:yztz-dev-3grjzqef57606d08}")
    private String env;

    @Value("${cloud.appid:wx522a08e066f0ef7e}")
    private String appid;

    @Value("${cloud.secret:281685540779995dea7d672e3de9b45d}")
    private String secret;


    public JSONObject minTenantAdd(SysTenant sysTenant){
        MiniTenant miniTenant = MiniTenant.build(sysTenant);
        return add("sys_tenant",miniTenant);
    }
    public JSONObject minTenantRemove(Long id){
        return removeById("sys_tenant",id);
    }
    public JSONObject minTenantUpdate(SysTenant sysTenant){
        MiniTenant miniTenant = MiniTenant.build(sysTenant);
        return updateById("sys_tenant",miniTenant);
    }






    public JSONObject miniAdminAdd(SysTenant sysTenant){
        MiniAdmin miniAdmin = MiniAdmin.build(sysTenant);
        return add("bx_admin",miniAdmin);
    }
    public JSONObject miniAdminRemoveByAdminId(Long id){
        return removeByWhere("bx_admin",
            "{ADMIN_ID:\"" + id + "\"}");
    }
    public JSONObject miniAdminUpdate(SysTenant sysTenant){

        JSONObject json = new JSONObject();
        json.put("ADMIN_NAME",sysTenant.getAdminName());
        json.put("ADMIN_PASSWORD",sysTenant.getAdminPassword());
        return updateByWhere("bx_admin",
            "{ADMIN_ID:\"" + sysTenant.getTenantId() + "\"}",JSONUtil.toJsonStr(json));
    }





//    public JSONObject miniBannerAdd(SysMiniBanner sysMiniBanner){
//        MiniBanner miniBanner = MiniBanner.build(sysMiniBanner);
//        return add("sys_banner",miniBanner);
//    }
//    public JSONObject miniBannerRemove(Long id){
//        return removeById("sys_banner",id);
//    }
//    public JSONObject miniBannerUpdate(SysMiniBanner sysMiniBanner){
//        MiniBanner miniBanner = MiniBanner.build(sysMiniBanner);
//        return updateById("sys_banner",miniBanner);
//    }








    public String getAccessToken(){

        String token = RedisUtils.getCacheObject(TOKEN_KEY );
        if(StringUtils.isEmpty(token)) {
            JSONObject json = new JSONObject();
            json.put("grant_type","client_credential");
            json.put("appid",appid);
            json.put("secret",secret);
            json.put("force_refresh",true);

            JSONObject jsonObject = null;
            try {
                String resToken = HttpUtil.post(ACCESS_TOKEN_GET, json.toString());
                jsonObject = new JSONObject(resToken);
                token = jsonObject.getStr("access_token");
                RedisUtils.setCacheObject(TOKEN_KEY, token, Duration.ofSeconds(7100));
            } catch (Exception e) {
                log.error("CloudApi getAccessToken error," + jsonObject.toString(),e);
            }

        }
        return token;
    }

    public String getToken(){

        String token = RedisUtils.getCacheObject(TOKEN_KEY );
        if(StringUtils.isEmpty(token)) {
            String url   = String.format(TOKEN_GET, appid,secret);
            JSONObject jsonObject = null;
            try {
                String resToken = HttpUtil.get(url);
                jsonObject = new JSONObject(resToken);
                token = jsonObject.getStr("access_token");
                RedisUtils.setCacheObject(TOKEN_KEY, token, Duration.ofSeconds(TOKEN_MIN));
            } catch (Exception e) {
                log.error("CloudApi getToken error," + jsonObject.toString(),e);
            }

        }
        return token;
    }
    public JSONObject add(String tableName,MiniBase miniBase){
        String url = getDbAddUrl();
        RequestJson miniJson = RequestJson.builder()
            .env(env)
            .query(String.format(DB_ADD_SQL, tableName, JSONUtil.toJsonStr(miniBase)))
            .build();
        String resultStr = HttpUtil.post(url,JSONUtil.toJsonStr(miniJson));
        return new JSONObject(resultStr);
    }
    public JSONObject removeById(String tableName,Long id){
        String url = getDbRemoveUrl();
        RequestJson miniJson = RequestJson.builder()
            .env(env)
            .query(String.format(DB_REMOVE_KEY_SQL,tableName, id.toString()))
            .build();
        String resultStr = HttpUtil.post(url,JSONUtil.toJsonStr(miniJson));
        return new JSONObject(resultStr);
    }
    public JSONObject removeByWhere(String tableName,String where){
        String url = getDbRemoveUrl();
        RequestJson miniJson = RequestJson.builder()
            .env(env)
            .query(String.format(DB_REMOVE_SQL,tableName, where))
            .build();
        String resultStr = HttpUtil.post(url,JSONUtil.toJsonStr(miniJson));
        return new JSONObject(resultStr);
    }
    public JSONObject updateById(String tableName, MiniBase miniBase){
        String url = getDbUpdateUrl();

        RequestJson miniJson = RequestJson.builder()
            .env(env)
            .query(String.format(DB_UPDATE_KEY_SQL, tableName, miniBase.get_id(), JSONUtil.toJsonStr(miniBase)))
            .build();
        String resultStr = HttpUtil.post(url,JSONUtil.toJsonStr(miniJson));
        return new JSONObject(resultStr);
    }
    public JSONObject updateByWhere(String tableName,String where, String updateStr){
        String url = getDbUpdateUrl();

        RequestJson miniJson = RequestJson.builder()
            .env(env)
            .query(String.format(DB_UPDATE_SQL, tableName, where, updateStr))
            .build();
        String resultStr = HttpUtil.post(url,JSONUtil.toJsonStr(miniJson));
        return new JSONObject(resultStr);
    }
    private String getDbAddUrl (){
        return DB_ADD + getAccessToken();
    }
    private String getDbUpdateUrl (){
        return DB_UPDATE + getAccessToken();
    }
    private String getDbRemoveUrl (){
        return DB_REMOVE + getAccessToken();
    }

}
